#include "bldc_foc.h"
int (*BLDC_ParamInquire)(BLDC_Device *);

int BLDC_Run(BLDC_Device *device)
{
    BLDC_ParameterSend(device, BLDC_CommandRun);
    device->current_status |= BLDC_STATUS_RUN;
    return 0;
}

int BLDC_Stop(BLDC_Device *device)
{
    BLDC_ParameterSend(device, BLDC_CommandStop);
    device->current_status &= ~BLDC_STATUS_RUN;
    device->initialized     = BLDC_Uninitialized;
    return 0;
}

int BLDC_Initialize(BLDC_Device *device)
{
    device->ref_position = 0x7fff;
    BLDC_ParameterSend(device, BLDC_CommandSetOrigin);
    for(int delay; delay<0xFFFF; delay++);
    BLDC_SendParam(device);
    for(int delay; delay<0xFFFF; delay++);
    BLDC_Run(device);
    device->initialized = BLDC_Initialized;
    return 0;
}

int BLDC_SetOrigin(BLDC_Device *device)
{
    BLDC_ParameterSend(device, BLDC_CommandSetOrigin);
    return 0;
}

int BLDC_SetParam(BLDC_Device *device)
{
    BLDC_ParameterSend(device, NULL);
    return 0;
}

int BLDC_GetParam(BLDC_Device *device)
{
    if((device->current_status & BLDC_STATUS_MASK) == BLDC_STATUS_RUN)
        BLDC_Run(device);
    else
        BLDC_Stop(device);
    return 0;
}

int BLDC_SendParam(BLDC_Device *device)
{
    BLDC_ParameterSend(device, NULL);
    return 0;
}

int BLDC_SetRunMode(BLDC_Device *device, BLDC_RunMode_TypeDef runmode)
{
    if((device->current_status & BLDC_MODE_MASK) == runmode)
    {
        return 0;
    }
    else
    {
        switch (runmode)
        {
        case BLDC_RunMode_Position:
                //position  mode
                RS485_SetRunMode('p');
                device->current_status &= ~BLDC_MODE_MASK;
                device->current_status |= runmode;
            break;
        case BLDC_RunMode_Speed :
                //speed mode
                RS485_SetRunMode('s');
                device->current_status &= ~BLDC_MODE_MASK;
                device->current_status |= runmode;
            break;
        case BLDC_RunMode_Moment :
                //current mode
                RS485_SetRunMode('c');
                device->current_status &= ~BLDC_MODE_MASK;
                device->current_status |= runmode;
            break;
        default:
            break;
        }
        return 0;
    }
}
